import { reactive } from 'vue'
import { defineStore } from 'pinia'
import type { IUser } from '@/types'
import { Md5 } from 'ts-md5'

export const useUserStore = defineStore(
  'user',
  () => {
    const salt = 'This Is a God Damn Salt!!'

    /* state */
    const user = reactive<IUser>({
      isLogin: false,
      phone: '',
      password: '',
      nickname: '',
      favorite: [],
      avatar: ''
    })
    /* getters */
    /* actions */
    // 注册
    function register(userData: IUser) {
      user.phone = userData.phone
      user.nickname = userData.nickname
      // 密码加密
      const md5 = new Md5()
      const md5Password = md5.appendStr(userData.password).appendStr(salt).end()
      user.password = md5Password
    }
    // 登录
    function login(userData: IUser) {
      const md5 = new Md5()
      const md5Password = md5.appendStr(userData.password).appendStr(salt).end()
      if (user.phone === userData.phone && user.password === md5Password) {
        user.isLogin = true
        return true
      }
      return false
    }
    // 退出登录
    function logout() {
      user.isLogin = false
    }

    return { user, register, login, logout }
  },
  {
    persist: true
  }
)
